/*
 * Powered By XY
 * Since 2020
 */

package com.xy.biz.rs.manager.impl;

import com.xy.biz.rs.manager.RecordTemplateMinioManager;
import com.xy.lang.domain.Result;
import com.xy.tool.gid.service.GidService;
import com.xy.tool.minio.util.FileUtility;
import com.xy.tool.minio.util.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

/**
 * @date 2022-1-4
 */
@Slf4j
@Service
public class RecordTemplateMinioManagerImpl implements RecordTemplateMinioManager {

    @Autowired
    private GidService gidService;
    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private FileUtility fileUtility;

    @Override
    public Result<?> upload(MultipartHttpServletRequest request) {
        MultipartFile picture = request.getFile("picture");
        if (Objects.isNull(picture)) {
            return Result.ofBadRequest("picture is null");
        }
        InputStream inputStream;
        try {
            inputStream = picture.getInputStream();
        } catch (IOException e) {
            log.error(e.getMessage());
            return Result.ofBadRequest("未获取到图片流！");
        }
        String curExt = fileUtility.getFileExtension(picture.getOriginalFilename());
        String tmpFileName = gidService.generate() + curExt;
        try {
            minioUtil.uploadFile(inputStream, tmpFileName, MinioUtil.templateImage);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.ofBadRequest("图片上传失败！");
        }
        String objectUrl;
        try {
            objectUrl = minioUtil.getObjectURL(MinioUtil.templateImage, tmpFileName, null);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.ofNotFound("获取图片失败：" + tmpFileName);
        }
        if (!StringUtils.hasText(objectUrl)) {
            return Result.ofNotFound("未找到图片：" + tmpFileName);
        }
        objectUrl = objectUrl.contains("?") ? objectUrl.substring(0, objectUrl.indexOf("?")) : objectUrl;
        return Result.success(objectUrl);
    }
}
